package com.dongqi.myblog.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongqi.myblog.po.TComment;
import com.dongqi.myblog.po.TUser;
import com.dongqi.myblog.service.TCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dongqi
 * @since 2020-08-03
 */
@Controller
public class TCommentController {

    @Autowired
    private TCommentService commentService;

    @Value("${comment.avatar}")
    private String defaultAvatar;

    /**
     * 获取评论列表的方法
     */
    @GetMapping("/comments/{blogId}")
    public String comments(@RequestParam(defaultValue = "0")Long pageNo,
                           @RequestParam(defaultValue = "10")Long pageSize,
                           @PathVariable Long blogId,
                           Model model){
        Page<TComment> page = new Page<>(pageNo,pageSize);
        List<TComment> comments = commentService.getComments(page,blogId);
        model.addAttribute("comments",comments);
        return "blog :: commentList";
    }

    /**
     * 保存评论信息
     */
    @PostMapping("/comments")
    public String post(TComment comment,HttpSession session){

        //区别管理员评论
        TUser user = (TUser) session.getAttribute("user");
        if (user!=null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        } else {
            comment.setAvatar(defaultAvatar);
            comment.setAdminComment(false);
        }
        commentService.saveComment(comment);
        return "redirect:/comments/"+comment.getBlogId();
    }


}

